package lock;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class SegmentLockTest {

    // 使用 ConcurrentHashMap
    private static final ConcurrentHashMap<Integer, String> map = new ConcurrentHashMap<>();

    // 计数器，跟踪读写操作的次数
    private static final AtomicInteger readCounter = new AtomicInteger(0);
    private static final AtomicInteger writeCounter = new AtomicInteger(0);

    // 写操作任务
    static class WriteTask implements Runnable {
        private final int key;
        private final String value;

        WriteTask(int key, String value) {
            this.key = key;
            this.value = value;
        }

        @Override
        public void run() {
            map.put(key, value);
            //这个增量也会比较
            writeCounter.incrementAndGet();
        }
    }

    // 读操作任务
    static class ReadTask implements Runnable {
        private final int key;

        ReadTask(int key) {
            this.key = key;
        }

        @Override
        public void run() {
            map.get(key);
            //这个增量也会比较
            readCounter.incrementAndGet();
        }
    }

    // 测试方法，模拟并发读写
    public static void testConcurrentOperations(int numThreads) throws InterruptedException {
        ExecutorService executor = Executors.newFixedThreadPool(numThreads);

        // 启动一些写操作任务
        for (int i = 0; i < numThreads / 2; i++) {
            int key = i;
            String value = "Value_" + i;
            executor.submit(new WriteTask(key, value));
        }

        // 启动一些读操作任务
        for (int i = 0; i < numThreads / 2; i++) {
            int key = i;
            executor.submit(new ReadTask(key));
        }

        executor.shutdown();
        executor.awaitTermination(1, TimeUnit.MINUTES);
    }

    public static void main(String[] args) throws InterruptedException {
        // 测试不同线程数下的表现
        int numThreads = 100;
        testConcurrentOperations(numThreads);
        System.out.println("Total reads: " + readCounter.get());
        System.out.println("Total writes: " + writeCounter.get());
    }
}
